using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Security.Permissions;
using System.Security.AccessControl;
using System.Diagnostics;
using System.Configuration;
using System.Collections.Specialized;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using UselessExplorer.Properties;

namespace UselessExplorer
{
    public partial class MainWindow : Form
    {
        clsGlobal global = clsGlobal.Instance;

        private int childFormNumber = 0;

        public MainWindow()
        {
            InitializeComponent();
        }
        #region PreDefinedCode
        private void ShowNewForm(object sender, EventArgs e)
        {
            // Create a new instance of the child form.
            Form childForm = new Form();
            // Make it a child of this MDI form before showing it.
            childForm.MdiParent = this;
            childForm.Text = "Window " + childFormNumber++;
            childForm.Show();
        }

        private void OpenFile(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            openFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                string FileName = openFileDialog.FileName;
                // TODO: Add code here to open the file.
            }
        }

        private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            saveFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
            if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                string FileName = saveFileDialog.FileName;
                // TODO: Add code here to save the current contents of the form to a file.
            }
        }

        private void ExitToolsStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void CutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // TODO: Use System.Windows.Forms.Clipboard to insert the selected text or images into the clipboard
        }

        private void CopyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // TODO: Use System.Windows.Forms.Clipboard to insert the selected text or images into the clipboard
        }

        private void PasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // TODO: Use System.Windows.Forms.Clipboard.GetText() or System.Windows.Forms.GetData to retrieve information from the clipboard.
        }

        private void ToolBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStrip.Visible = toolBarToolStripMenuItem.Checked;
        }

        private void StatusBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            statusStrip.Visible = statusBarToolStripMenuItem.Checked;
        }

        private void CascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.Cascade);
        }

        private void TileVerticleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileVertical);
        }

        private void TileHorizontalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileHorizontal);
        }

        private void ArrangeIconsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.ArrangeIcons);
        }

        private void CloseAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form childForm in MdiChildren)
            {
                childForm.Close();
            }
        }
        #endregion

        private void MainWindow_Load(object sender, EventArgs e)
        {
            this.Text = UselessExplorer.Properties.UselessResources.frmExplorerWinTitle;

#if !DEBUG
            
            // Splash Screen
            this.Hide();
            frmSplash fs = new frmSplash();
            fs.ShowDialog();
            this.Show();
#endif
            // Intitalisation of Configuration
            global.initialiseTrace();
            global.Extenstions = frmAllowedExtensions.readConfiguration();

            dirTree.ImageList = folderImageList;
            string path = String.Empty;
            tsLblPathView.Text = String.Empty;
            
            foreach (string drive in Directory.GetLogicalDrives())
            {
                path = drive;
                cbDriveList.Items.Add(path);
            }

            cbDriveList.SelectedItem = cbDriveList.Items[0];
        }

        private void toolStripSearchReplace_Click(object sender, EventArgs e)
        {
            frmSearchReplace srchReplace = new frmSearchReplace();
            srchReplace.ShowDialog();
        }

        private void dirTree_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            dirTree.SelectedNode = e.Node;
            dirTree.SelectedNode.ImageIndex = 1;
        }

        private void toolStripComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            InitLoad();
        }

        DirectoryTree dirTree = new DirectoryTree();
        private void InitLoad()
        {
            string val = cbDriveList.SelectedItem.ToString();
            lvFiles.Items.Clear();
            dirTree.Drive = val.Substring(0, 2);

            dirTree.Size = new Size(this.Width - 50, this.Height - 60);
            dirTree.Location = new Point(5, 5);
            this.splitContainer1.Panel1.Controls.Add(dirTree);
            dirTree.Dock = DockStyle.Fill;
            dirTree.NodeMouseClick += new TreeNodeMouseClickEventHandler(dirTree_NodeMouseClick);
            dirTree.AfterSelect += new TreeViewEventHandler(dirTree_AfterSelect);
            dirTree.BeforeSelect += new TreeViewCancelEventHandler(dirTree_BeforeSelect);
            dirTree.ShowPlusMinus = false;
            dirTree.ContextMenuStrip = contextMenuTreeView;

        }

        void dirTree_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            e.Node.StateImageIndex = 0;
        }

        private void dirTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            loadFiles(dirTree.SelectedNode.FullPath, false);
            dirTree.SelectedNode = e.Node;
            dirTree.SelectedNode.ImageIndex = 0;
        }

        private void addExtension_Click(object sender, EventArgs e)
        {
            string initialPath = String.Format(@"{0}",dirTree.SelectedNode.FullPath);
            string filepath = initialPath + lvFiles.SelectedItems[0].Text.ToString();

            DirectoryInfo dirInfo = new DirectoryInfo(filepath);

            if (!global.IsExtensionRestricted(dirInfo.Extension))
            {
                int extensionCount = global.Extenstions.Length;
                string[] tempList = new string[extensionCount + 1];
                string[] temp = global.Extenstions;

                for (int i = 0; i < extensionCount; i++)
                {
                    tempList[i] = temp[i];
                }

                tempList[extensionCount] = dirInfo.Extension.ToLower();
                global.Extenstions = tempList;

                tsStatusLabel.Text = (global.SaveExtensions() == true) ? UselessResources.ExpAddExtnSuccess : UselessResources.ExpAddExtnFailed;
            }
            else
            {
                tsStatusLabel.Text = UselessResources.ExpAddExtnFailed;
            }
        }

        private void tsSplitButton_Click(object sender, EventArgs e)
        {
            frmAllowedExtensions fae = new frmAllowedExtensions();
            fae.ShowDialog();
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(UselessExplorer.Properties.UselessResources.ExpDelFolderWarning, "Info", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
            {
                DirectoryInfo dirInfo = new DirectoryInfo(dirTree.SelectedNode.FullPath.ToString());
                dirInfo.Delete(true);
                InitLoad();
                dirTree.Nodes[0].Expand();
                lvFiles.Items.Clear();
            }
        }

        private void loadFiles(string path, bool isRootNode)
        {
            try
            {
                this.lvFiles.Items.Clear();

                DirectoryInfo currentDir = new DirectoryInfo(path);
                lvFiles.Items.Clear();

                try
                {
                    foreach (DirectoryInfo dir in currentDir.GetDirectories())
                    {
                        ListViewItem item = new ListViewItem();
                        item.Text = dir.Name;
                        item.ImageIndex = 63;
                        item.Tag = dir;
                        lvFiles.Items.Add(item);
                    }
                }
                catch { }

                try
                {
                    int count = 0;
                    foreach (FileInfo file in currentDir.GetFiles())
                    {
                        ListViewItem item = new ListViewItem();
                        item.Text = file.Name;
                        item.Tag = file;
                        item.ImageIndex = global.GetIconIndex(file.Name);
                        lvFiles.Items.Add(item);

                        count++;
                        if (count == 100)
                        {
                            lvFiles.Refresh();
                            count = 0;
                        }
                    }

                }
                catch (FileNotFoundException)
                {
                    lvFiles.Items.Add(UselessResources.ExpFilesNotFound);
                }
                catch (UnauthorizedAccessException uae)
                {
                    dirTree.SelectedNode.Remove();
                    global.WriteLogs(Logger.LogsCategory.Exception, uae);
                }

            }
            catch (Exception ex)
            {
                global.WriteLogs(Logger.LogsCategory.Exception, ex);
            }
        }

        private void lvFiles_DoubleClick(object sender, EventArgs e)
        {
            if (lvFiles.SelectedItems[0].Tag.GetType() == typeof(DirectoryInfo))
            {
                string path = dirTree.SelectedNode.FullPath + @"\" + lvFiles.SelectedItems[0].Text;
                

                for (int Index = 0; Index < dirTree.SelectedNode.Nodes.Count; Index++)
                {
                    if (dirTree.SelectedNode.Nodes[Index].Text.Equals(lvFiles.SelectedItems[0].Text))
                    {
                        dirTree.SelectedNode = dirTree.SelectedNode.Nodes[Index];
                        dirTree.SelectedNode.Expand();
                        break;
                    }
                }
            }
        }

        private void deleteToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            string fileName = lvFiles.SelectedItems[0].Text.ToString();
            string fullPath = dirTree.SelectedNode.FullPath + @"\" + fileName;

            if (!isDirectory(fullPath))
            {
                FileInfo fi = new FileInfo(fullPath);
                fi.Delete();
                bool isRootNode = false;
                if (dirTree.SelectedNode.Text == cbDriveList.SelectedItem.ToString())
                    isRootNode = true;
                loadFiles(dirTree.SelectedNode.FullPath.ToString(), isRootNode);
            }
            else
            {
                DirectoryInfo dinfo = new DirectoryInfo(fullPath);
                dinfo.Delete(true);
                loadFiles(dirTree.SelectedNode.FullPath, false);
                dirTree.RefreshDisplay();
            }
        }

        private void propertiesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string filePath;
            if (lvFiles.SelectedItems[0] == null)
            {
                filePath = dirTree.SelectedNode.FullPath;
                frmProperties fp = new frmProperties(filePath, true);
                fp.ShowDialog();
            }
            else
            {
                filePath = dirTree.SelectedNode.FullPath + @"\" + lvFiles.SelectedItems[0].Text;
                if (!isDirectory(filePath))
                {
                    frmProperties fp = new frmProperties(filePath, false);
                    fp.ShowDialog();
                }
                else
                {
                    frmProperties fp = new frmProperties(filePath, isDirectory(filePath));
                    fp.StartPosition = FormStartPosition.CenterParent;
                    fp.ShowDialog();
                }
            }
        }

        private void tmrClean_Tick(object sender, EventArgs e)
        {
            tmrClean.Stop();
            tmrClean.Enabled = false;
            tsStatusLabel.Text = "";
        }

        private void fileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmPromptBox fpb = frmPromptBox.Instance;
            fpb.IsFolder = false;
            fpb.ShowDialog();

            if (fpb.FileName != null)
            {
                string file = fpb.FileName;
                string dirPath = dirTree.SelectedNode.FullPath;
                FileInfo fInfo = new FileInfo(dirPath + @"\" + file);
                FileStream fstr = fInfo.Create();
                fstr.Close();

                bool isRootNode = false;

                isRootNode = (dirTree.SelectedNode.Text == cbDriveList.SelectedItem.ToString()) ? true : false;
                loadFiles(dirTree.SelectedNode.FullPath.ToString(), isRootNode);
            }
        }

        private void propertiesToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            frmProperties fp = new frmProperties(dirTree.SelectedNode.FullPath, true);
            fp.ShowDialog();
        }

        private void folderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmPromptBox fpb = frmPromptBox.Instance;
            fpb.IsFolder = true;
            fpb.ShowDialog();

            if (fpb.FileName != null)
            {
                string folderName = fpb.FileName;
                string dirPath = dirTree.SelectedNode.FullPath;
                Directory.CreateDirectory(dirPath + @"\" + folderName);

                dirTree.Refresh();
                dirTree.SelectedNode.Expand();
            }

        }

        private void allowedExtensionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmAllowedExtensions fae = new frmAllowedExtensions();
            fae.ShowDialog();
        }

        private void MainWindow_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode.ToString() == "K")
            {
                frmAllowedExtensions fae = new frmAllowedExtensions();
                fae.ShowDialog();
            }
        }

        private void searchAndReplaceMultipleFilesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmSearchReplace fsr = new frmSearchReplace();
            fsr.Show();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            frmFtpControl ftp = new frmFtpControl();
            ftp.Show();
        }

        private void createFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Will be implemented soon");
        }

        private void toolStripDocumentation_Click(object sender, EventArgs e)
        {
            frmVB6Documenter doc = new frmVB6Documenter();
            doc.Show();
        }

        private void networkMonitoringToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmNetwrkStatus netwrk = new frmNetwrkStatus();
            netwrk.Show();
        }

        private void vB6DocumentorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmVB6Documenter vb6doc = new frmVB6Documenter();
            vb6doc.Show();
        }

        private void tsNetworkMonitor_Click(object sender, EventArgs e)
        {
            frmNetwrkStatus network = new frmNetwrkStatus();
            network.Show();
        }

        private void ftpClientToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmFtpControl ftp = new frmFtpControl();
            ftp.Show();
        }

        private void lvFiles_SelectedIndexChanged(object sender, EventArgs e)
        {
            openFile(MouseButtons);
        }

        private void openFile(MouseButtons mb)
        {
            bool flag = true;
            try
            {
                if (mb == MouseButtons.Left)
                {
                    if (lvFiles.SelectedItems != null && lvFiles.SelectedItems.Count > 0) //&& !fileList.SelectedItem.ToString().Equals(UselessResources.ExpFilesNotFound))
                    {
                        string initialPath = dirTree.SelectedNode.FullPath;
                        string filepath = initialPath + @"\" + lvFiles.SelectedItems[0].Text.ToString();

                        if (!isDirectory(filepath))
                        {
                            for (int i = 0; i < contextMenuListboxItem.Items.Count; i++)
                            {
                                if (contextMenuListboxItem.Items[i].Text.Equals("Add Extension"))
                                {
                                    contextMenuListboxItem.Items.RemoveAt(i);
                                }
                            }

                            lvFiles.ContextMenuStrip = contextMenuListboxItem;
                            tsLblPathView.Text = filepath;
                            DirectoryInfo dirInfo = new DirectoryInfo(filepath);

                            foreach (string extension in global.Extenstions)
                            {
                                flag = (dirInfo.Extension.ToUpper() != extension.ToUpper()) ? true : false;
                                if (!flag)
                                    break;
                            }

                            if (!flag)
                            {
                                frmTxtViewer txtView = new frmTxtViewer(filepath);
                                txtView.ShowDialog();
                            }
                            else
                            {
                                contextMenuListboxItem.Items.Add("Add Extension", null, new EventHandler(addExtension_Click));
                                tsStatusLabel.Text = UselessResources.ExpFileViewFailed;
                                tsStatusLabel.ForeColor = Color.Red;
                                tmrClean.Enabled = true;
                                tmrClean.Start();
                            }
                        }
                    }
                    else
                    {
                        lvFiles.ContextMenuStrip = contextMenuListboxItem;
                    }

                }
                else if (mb == MouseButtons.Right && lvFiles.SelectedItems.Count > 0)
                {
                    lvFiles.ContextMenuStrip = contextMenuListboxItem;
                }
                else
                {
                    lvFiles.ContextMenuStrip = contextMenuListboxAll;
                }
            }
            catch (Exception ex)
            {
                global.WriteLogs(Logger.LogsCategory.Exception, ex);
            }
        }

        private void errorLogsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmTraces trace = new frmTraces();
            if (!trace.IsDisposed)
            {
                global.initialiseTrace(trace);
                trace.Show();
            }
        }

        private void lvFiles_MouseDown(object sender, MouseEventArgs e)
        {
            if (MouseButtons == MouseButtons.Right && lvFiles.SelectedItems.Count == 0)
                lvFiles.ContextMenuStrip = contextMenuListboxAll;
        }

        private bool isDirectory(string path)
        {
           return Directory.Exists(path);
        }

        private void deleteFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Will be implemented soon");
        }

        private void propertiesToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Will be implemented soon");
        }

    }
}
